package com.authine.cloudpivot.engine.plugin.service.impl.wechatmsg;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.YAMLConfig;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
//import com.authine.cloudpivot.web.api.domain.Constants;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SendWechatMSG {

    public String getAccessToken(YAMLConfig config){
        log.info("进入getAccessToken方法，参数corpid为：" + config.getCorpid()+",参数corpsecret为:"+config.getCorpsecret());
        Map<String,Object> param = new HashMap<>();

        String realTokenUrl= config.getWx_token_url();
        param.put("corpid",config.getCorpid());
        param.put("corpsecret",config.getCorpsecret());
        String response = HttpUtil.get(realTokenUrl, param);
        JSONObject jsonObject = JSONObject.fromObject(response);
        log.info("获取accessToken响应: "+response);
        String token = jsonObject.get("access_token")==null?null:String.valueOf(jsonObject.get("access_token"));
        if (StringUtils.isBlank(token)) {
            log.warn("获取accessToken失败，错误信息：" + response);
            //throw new AccessTokenInvalidateException(" accessToken 非法");
        }
        log.info("获取Token成功: {}", token);
        log.info("------------------getAccessToken end ----------------------------" );
        return token;
    };

    public String getUserInfo(String accessToken,String userId){
        log.info("getUserInfo，accessToken：" + accessToken+",参数userId为:"+userId);
        Map<String,Object> param = new HashMap<>();

        String realUserUrl= "";
        param.put("access_token",accessToken);
        param.put("userid",userId);
        String response = HttpUtil.get(realUserUrl, param);
        JSONObject jsonObject = JSONObject.fromObject(response);
        log.info("获取user 响应: "+response);
        String token = jsonObject.get("access_token")==null?null:String.valueOf(jsonObject.get("access_token"));
        if (StringUtils.isBlank(token)) {
            log.warn("获取accessToken失败，错误信息：" + response);
            //throw new AccessTokenInvalidateException(" accessToken 非法");
        }
        log.info("获取Token成功: {}", token);
        log.info("------------------getAccessToken end ----------------------------" );
        return token;
    };

    public void sendWXMSG(YAMLConfig config, String userId, String msgType, String content)
    {

        TextMessage textMessage = new TextMessage();
        textMessage.setTouser(userId);
        textMessage.setMsgtype(msgType);
        textMessage.setAgentid(config.getAgeng_id());

        Text text = new Text();
        text.setContent(content);
        textMessage.setText(text);
        SendWechatMSG sendWechatMSG = new  SendWechatMSG();
        //将对象转json字符串
        String textJson = JSON.toJSONString(textMessage);
        //获取AccessToken
        String accessToken = sendWechatMSG.getAccessToken(config);
        String sendUrl = config.getWx_msg_url().replace("ACCESS_TOKEN", accessToken);
        //发送post请求
        SendWechatMSG.sendPost(sendUrl, textJson);
    }

    public static com.alibaba.fastjson.JSONObject sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        com.alibaba.fastjson.JSONObject jsonObject = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
//            conn.addRequestProperty("Cookie", "stay_login=1 smid=DumpWzWQSaLmKlFY1PgAtURdV_u3W3beoei96zsXkdSABwjVCRrnnNBsnH1wGWI0-VIflgvMaZAfli9H2NGtJg id=EtEWf1XZRLIwk1770NZN047804");//设置获取的cookie
            // 获取URLConnection对象对应的输出流（设置请求编码为UTF-8）
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取请求返回数据（设置返回数据编码为UTF-8）
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject;
    }

}
